// pages/music-player/index.js
import { audioContext, playerStore } from '../../store/index'

const playModeNames = ["order", "repeat","random" ]

Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    currentSong: {},
    durationTime: 0,
    lyricInfos: [],

    currentTime: 0,
    currentLyricText: "",
    currentLyricIndex: 1,

    playModeIndex: 0,
    playModeName: 'order',
    songPlayList:[],
    songPlayListIndex:0,

    currentPage: 0,
    contentHeight: 0,
    sliderValue: 0,
    lyricScrollTop: 0,
    isShowLyric: true,
    isSliderChanging: false,
    isPlaying: true,
    playingName:'pause'

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 1.获取传入的id
    const id = options.id

    // 2.获取内容高度，除去状态栏等高度
    const globalData = getApp().globalData
    const screenHeight = globalData.screenHeight //屏幕高度
    const statusBarHeight = globalData.statusBarHeight //屏幕宽度
    const navBarHeight = globalData.navBarHeight //状态栏高度
    const deviceRadio = globalData.deviceRadio //屏幕宽高比
    const contentHeight = screenHeight - statusBarHeight - navBarHeight
    this.setData({ contentHeight, isShowLyric: deviceRadio >= 2 })

    // 3.监听store中歌曲数据的变化
    this.setupPlayerStoreListener()

    //5.audioContext的事件监听
    // this.setupAudioContextLinster()

  },


  //========================= audio监听(此部分可以放入store中) =============================
  // setupAudioContextLinster:function(){
  //   // 监听时间改变
  //   audioContext.onTimeUpdate(() => {
  //     // 1.获取当前时间
  //     const currentTime = audioContext.currentTime * 1000
  //     // 2.根据当前时间修改currentTime、sliderValue
  //     if (!this.data.isSliderChanging) {
  //       const sliderValue = currentTime / this.data.durationTime * 100
  //       this.setData({ sliderValue, currentTime })
  //     }
  //     // 3.根据当前时间去查找播放的歌词
  //     if(!this.data.lyricInfos.length) return
  //     for (let i = 0; i < this.data.lyricInfos.length; i++) {
  //       const lyricInfo=this.data.lyricInfos[i]
  //       // 当前时间小于循环的歌词时间，显示上一行歌词
  //       if (currentTime<lyricInfo.time) {
  //         const currentLyricIndex=i-1
  //         //避免多次赋值，判断当前歌曲索引是否重合
  //         if (this.data.currentLyricIndex!==currentLyricIndex) {
  //           const currentLyric=this.data.lyricInfos[currentLyricIndex]

  //           this.setData({
  //             currentLyricText:currentLyric.text,
  //             currentLyricIndex,
  //             lyricScrollTop:currentLyricIndex*35
  //           })
  //         }
  //         break;
  //       }
  //     }
  //   })
  // },

  //========================= 事件处理 =============================
  //手动移动滑动的时候
  handleSliderChanging: function (event) {
    // 阻止滑块根据进度自动改变
    this.setData({ isSliderChanging: true })
    //根据当前滑块值更改 歌曲播放进度
    const sliderValue = event.detail.value
    const currentTime = this.data.durationTime * sliderValue / 100
    this.setData({
      currentTime, isSliderChanging: false
    })
  },

  // 点击滑块后改变
  handleSliderChange: function (event) {
    //1.获取slider变化的值
    const sliderValue = event.detail.value

    // 2.计算需要播放的currentTime
    const currentTime = this.data.durationTime * sliderValue / 100
    this.setData({ currentTime, isSliderChanging: false })

    // 3.设置context播放currentTime位置的音乐
    // audioContext.pause()//暂停
    audioContext.seek(currentTime / 1000) //单位 s，精确到小数点后三位

    // 4.记录最新的sliderValue
    this.setData({ sliderValue })
    this.setData({ isChanging: false })
  },

  //Tab滑动事件处理
  handleSwiperChange: function (event) {
    const currentPage = event.detail.current
    this.setData({ currentPage })
  },

  //返回事件处理
  handleBackBtnClick: function () {
    wx.navigateBack()
  },

  // 切换模式按钮
  handleModeBtnClick: function () {
    //计算最新的播放模式
    let currentModeIndex = this.data.playModeIndex + 1
    if(currentModeIndex===3) currentModeIndex = 0
    // 设置playerStore中的播放模式
    playerStore.setState("playModeIndex",currentModeIndex)
  },

  //暂停/播放按钮
  handlePlayBtnClick: function () {
   playerStore.dispatch("changeMusicPlayStatusAction",this.data.isPlaying)
  },
 
  //上一首音乐
  handlePrevBtnClick:function(){
     playerStore.dispatch("changeNewMusicAction",false)
  },
  //下一首音乐
  handleNextBtnClick:function(){
    playerStore.dispatch("changeNewMusicAction")
  },
 

  // 监听store中相关数据
  setupPlayerStoreListener: function () {
    //监听 歌曲详情、歌曲时长、歌词数据
    playerStore.onStates(["currentSong", "durationTime", "lyricInfos"], ({
      currentSong,
      durationTime,
      lyricInfos
    }) => {
      if (currentSong) this.setData({ currentSong })
      if (durationTime) this.setData({ durationTime })
      if (lyricInfos) this.setData({ lyricInfos })
    })
    // 监听 播放时间、当前歌词索引、当前歌词
    playerStore.onStates(["currentTime", "currentLyricIndex", "currentLyricText"], ({
      currentTime,
      currentLyricIndex,
      currentLyricText
    }) => {

      //时间变化
      if (currentTime!==undefined && !this.data.isSliderChanging) {
        const sliderValue = currentTime / this.data.durationTime * 100
        this.setData({ sliderValue, currentTime })
      }
      // 歌词变化
      if (currentLyricIndex) {
        this.setData({ currentLyricIndex, lyricScrollTop: currentLyricIndex * 35 })
      }
      if (currentLyricText) this.setData({ currentLyricText })
    })
    //监听播放模式相关数据
    playerStore.onStates(["playModeIndex","isPlaying"], ({
      playModeIndex,
      isPlaying
    }) => {
      if (playModeIndex!==undefined) {
        this.setData({ 
        playModeIndex, 
        playModeName: playModeNames[playModeIndex]
       })
      }
      if (isPlaying !==undefined) {
        this.setData({
          isPlaying,
          playingName:isPlaying?'pause':'resume'})
      }
    })
  }
})